package com.salmon.common.utils;

import org.springframework.http.HttpStatus;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.ServletWebRequest;

public class WebUtils {

    /**
     * 判断是否是Ajax请求
     * @param request ServletWebRequest
     * @return 返回true代码是ajax请求，false表示请求是传统的 同步HTTP请求
     */
    public static boolean isAjax(ServletWebRequest request) {
        return request.getHeader("X-Requested-With") != null
                && "XMLHttpRequest".equalsIgnoreCase(request.getHeader("X-Requested-With"));
    }

    public static HttpStatus getStatus(ServletWebRequest request) {
        Integer statusCode = (Integer) request
                .getAttribute("javax.servlet.error.status_code", RequestAttributes.SCOPE_REQUEST);
        if (statusCode == null) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
        try {
            return HttpStatus.valueOf(statusCode);
        }
        catch (Exception ex) {
            return HttpStatus.INTERNAL_SERVER_ERROR;
        }
    }
}
